import React, { useState, useEffect } from 'react'
import './customer.css'
import { NavBar, SearchBar, Toast, Space, Button } from 'antd-mobile'
import { useNavigate, useLocation } from 'react-router-dom'
import axios from 'axios';
export default function Customer() {
    const navigate = useNavigate()
    const location = useLocation()
    // console.log(location.state.data);
    const [thisdata, setThisdata] = useState(location.state.data)

    const back = () => {
        navigate(-1)
    }
    const formatTime = (date) => {
      if (!date) {
        const data = new Date()
        const hours = String(data.getHours()).padStart(2, '0');
        const minutes = String(data.getMinutes()).padStart(2, '0');
        return `${hours}:${minutes}`;
      }else{
        const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
      }
      
    };
    const [ChatHistory, setChatHistory] = useState([
      {
        time:formatTime(),
        type:'customer',
        img:"https://cdn8.axureshop.com/demo2024/2322481/images/%E5%AE%A2%E6%9C%8D/u1929.svg",
        content:'亲，很高兴为您服务，请问您要咨询什么问题呢?'
      }
    ])
    const st = () =>{
      const histy = localStorage.getItem(thisdata.shopid._id)
      if(histy){
        setChatHistory(JSON.parse(histy))
      }else{
        localStorage.setItem(thisdata.shopid._id,JSON.stringify(ChatHistory))
      }
    }

    const [inputText, setInputText] = useState('');
    const [responseData, setResponseData] = useState(null);
    const handleSubmit = async () => {
    // e.preventDefault();
    try {
      let newdata = ChatHistory;
      newdata.push({
        time:formatTime(),
        type:'user',
        img:"https://cdn8.axureshop.com/demo2024/2322481/images/%E5%AE%A2%E6%9C%8D/u1926.svg",
        content:inputText
      })
      setChatHistory(newdata)
      localStorage.setItem(thisdata.shopid._id,JSON.stringify(newdata))
      const response = await axios.post('http://localhost:3000/chart', { text: inputText });
      let newcustorm = ChatHistory;
      newcustorm.push({
        time:formatTime(),
        type:'customer',
        img:"https://cdn8.axureshop.com/demo2024/2322481/images/%E5%AE%A2%E6%9C%8D/u1929.svg",
        content:response.data.data.choices[0].message.content
      })
      setChatHistory(newcustorm)
      localStorage.setItem(thisdata.shopid._id,JSON.stringify(newcustorm))
    } catch (error) {
      console.error('Error communicating with server:', error);
      setResponseData({ error: 'Failed to communicate with server' });
    }
    setInputText(''); // 清空输入框
  };
    useEffect(() => {
      st()
    },[]);
    return (
        <div className='customer'>
            <div className='customer-top'>
                <NavBar onBack={back} ><b>{thisdata.shopid.name}</b></NavBar>
            </div>
            <div className='customer-content'>
                {
                  ChatHistory.map((item,index)=>{
                    if(item.type==='user'){
                      return(
                        <div key={index} className='customer-content-box'>
                          <p>{item.time}</p>
                          <div className='customer-content-itema'>
                            <div className='customer-content-item-content'>{item.content}</div>
                            <div className='customer-content-item-img'>
                              <img src={item.img}/>
                            </div>
                          </div>
                        </div>)
                    }else{
                      return(
                        <div key={index} className='customer-content-box'>
                          <p>{item.time}</p>
                          
                          <div className='customer-content-item'>
                            <div className='customer-content-item-img'>
                              <img src={item.img}/>
                            </div>
                            <div className='customer-content-item-content'>{item.content}</div>
                          </div>
                        </div>)
                    }
                    
                  })
                }
            </div>
            <div className='customer-bottom'>
                <div>
                    <img src='https://cdn8.axureshop.com/demo2024/2322481/images/%E5%AE%A2%E6%9C%8D/u1887.svg'></img>
                </div>
                <div>
                    <SearchBar placeholder='想跟TA说点什么...' searchIcon={false}
                        style={{
                            width: '120%',
                            '--height': '2.5rem',
                            '--border-radius': '2rem',
                        }}
                        onChange={(e) => setInputText(e)}
                        onSearch={() => handleSubmit()}
                        value={inputText}
                         />
                </div>
                <div className='customer-bottom-right'>
                    <img src='https://cdn8.axureshop.com/demo2024/2322481/images/%E5%AE%A2%E6%9C%8D/u1886.svg'></img>
                    <img className='store_chard_item_img' src='../../../public/fair/customer.png'></img>
                </div>
            </div>
        </div>
    )
}
// AIChatComponent.jsx
// import React, { useState } from 'react';
// import axios from 'axios';
 
// const ChatComponent = () => {
//   const [inputText, setInputText] = useState('');
//   const [responseData, setResponseData] = useState(null);
 
//   const handleSubmit = async (e) => {
//     e.preventDefault();
//     try {
//       const response = await axios.post('http://localhost:3000/chart', { text: inputText });
//       setResponseData(response.data);
//     } catch (error) {
//       console.error('Error communicating with server:', error);
//       setResponseData({ error: 'Failed to communicate with server' });
//     }
//     setInputText(''); // 清空输入框
//   };
 
//   return (
//     <div>
//       <h1>讯飞对话功能</h1>
//       <form onSubmit={handleSubmit}>
//         <input
//           type="text"
//           value={inputText}
//           onChange={(e) => setInputText(e.target.value)}
//           placeholder="输入对话内容"
//         />
//         <button type="submit">发送</button>
//       </form>
//       {responseData && (
//         <div>
//           <h2>响应:</h2>
//           <pre>{JSON.stringify(responseData, null, 2)}</pre>
//         </div>
//       )}
//     </div>
//   );
// };
 
// export default ChatComponent;